<template>
    <el-form ref="formRef" :model="form" labelWidth="120px" label-suffix="：">
        <el-steps :active="active">
            <template v-for="(step, index) in steps" :key="index">
                <el-step>
                    <template #title>
                        <span class="step-title" @click="active = step.value">{{ step.title }}</span>
                    </template>
                </el-step>
            </template>
        </el-steps>
        <div v-show="active === 1" class="step1">
            <el-form-item label="节点名称">
                <el-input v-model="form.nodeName"/>
            </el-form-item>
            <el-form-item label="节点ID">
                <el-input v-model="form.typeConcatName" disabled/>
            </el-form-item>
            <el-form-item label="流输出" prop="isStream">
                <el-switch v-model="form.isStream" active-value="Y" inactive-value="N"></el-switch>
            </el-form-item>
            <el-form-item label="备注">
                <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
            </el-form-item>
            <dialog-footer @cancel="cancel" @ok="submitForm" ok-text="保存">
                <el-button type="success" @click="active = 2">下一步</el-button>
            </dialog-footer>
        </div>
        <div v-show="active === 2" class="step2">

<!--            <el-form-item label="运行方式">-->
<!--                <el-radio-group v-model="form.runMode">-->
<!--                    <el-radio label="本地"/>-->
<!--                    <el-radio label="远程服务器"/>-->
<!--                </el-radio-group>-->
<!--            </el-form-item>-->
<!--            <el-form-item label="切换工作目录">-->
<!--                <el-input v-model="form.workingDirectory"></el-input>-->
<!--                <div class="tip">空表示不切换</div>-->
<!--            </el-form-item>-->
<!--            <el-form-item label="脚本类型">-->
<!--                <el-select v-model="form.definitions.definition.script_type" placeholder="请选择脚本类型">-->
<!--                    <el-option label="linux" value="linux"></el-option>-->
<!--                    <el-option label="windows" value="windows"></el-option>-->
<!--                </el-select>-->
<!--            </el-form-item>-->
            <el-form-item label="创建新脚本">
                <el-radio-group v-model="form.selectScriptStatus" @change="changeScriptStatus">
                    <el-radio label="是"/>
                    <el-radio label="否，选择已有脚本"/>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="使用变量">
                <el-radio-group v-model="form.argumentsInFields" active-value="Y" inactive-value="N" @change="form.argumentsFields.argumentField = [{argumentFieldName: ''}]">
                    <el-radio value="Y">是</el-radio>
                    <el-radio value="N">否</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="变量" v-if="form.argumentsInFields === 'Y'">
                <div style="margin-bottom: 10px;">
                    <el-button
                        type="primary"
                        size="small"
                        @click="addField"
                    >新增字段</el-button>
                    <el-button
                        type="danger"
                        size="small"
                        @click="batchDelete"
                        :disabled="selectedRows.length === 0"
                    >删除选中</el-button>
                </div>
                <el-table :data="form.argumentFields.argumentField" style="width: 100%" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="30"/>
                    <el-table-column prop="name" label="字段名" width="320">
                        <template #default="scope">
                            <el-input v-model="scope.row.argumentFieldName"></el-input>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form-item>
            <el-form-item label="Shell脚本">
                <monaco-editor style="width:100%; height:400px"
                               v-model:value="form.processContent"
                               @changeTextArea="changeTextArea"
                               ref="monacoEditorRef"
                               class="script-textarea"
                               language='shell'
                ></monaco-editor>
                <div class="tip">提示：每行一句命令可以使用${变量}获取变量，默认为linux示例写法，windows示例 cmd/c echo "hello"每句必须要换行</div>
            </el-form-item>
<!--            <el-form-item label="结果保存" prop="result" required>-->
<!--                <el-input v-model="form.result"/>-->
<!--                <div class="tip">指定shell脚本执行完的结果保存的变量传入到下一节点中</div>-->
<!--            </el-form-item>-->
            <dialog-footer @ok="submitForm" @cancel="cancel" ok-text="保存">
                <el-button type="success" @click="active = 1">上一步</el-button>
                <el-button type="success" @click="active = 3">下一步</el-button>
            </dialog-footer>
        </div>
        <div v-show="active === 3" class="step3">
            <el-form-item label="输出分隔符">
                <el-input v-model="form.outputlinedelimiter"/>
            </el-form-item>
            <el-form-item label="结果保存">
                <el-input v-model="form.resultfieldname"/>
            </el-form-item>
            <el-form-item label="错误字段名">
                <el-input v-model="form.errorfieldname"/>
            </el-form-item>
            <el-form-item label="退出值字段名">
                <el-input v-model="form.exitvaluefieldname"/>
            </el-form-item>
            <dialog-footer @ok="submitForm" @cancel="cancel" ok-text="保存">
                <el-button type="success" @click="active = 2">上一步</el-button>
            </dialog-footer>
        </div>

    </el-form>

</template>

<script setup>
import {defineComponent, onMounted, reactive, ref} from 'vue';
import {flowServiceStore} from '@data/store/flow';
import {storeToRefs} from 'pinia';
import monacoEditor from "../disposition/monaco-editor.vue";
import {search, insert, deleteByIds, updateById, selectById,getDefaultScript} from "@data/api/data/datascript";
import {ElMessage} from "element-plus";

const flowCount = flowServiceStore();

const {flowData} = storeToRefs(flowCount);

const monacoEditorRef = ref(null);

defineComponent({
    name: 'ShellScript',
});

const steps = ref([
    { value: 1, title: '基础属性' },
    { value: 2, title: 'Shell脚本' },
    { value: 3, title: '输出参数' },
]);
const active = ref(1);

const props = defineProps({
    detailObject: {
        type: Object,
        default: () => {
        },
    },
})

const form = reactive({
    nodeName: '',
    name: '',
    type: 'ExecProcess',
    distribute: 'Y',
    copies: 1,
    GUI: {
        xloc: 1,
        yloc: 1,
        draw: 'Y'
    },

    selectScriptStatus: '',
    argumentsInFields: '',
    argumentFields: {
        argumentField:
            {
                argumentFieldName: '',
            }
    },
    processContent: '',
    processContentValue:'',

    outputlinedelimiter: '',
    resultfieldname: '',
    errorfieldname: '',
    exitvaluefieldname: '',

    failwhennotsuccess: 'Y',
});
const formRef = ref(null);

const emit = defineEmits(['cancel']);

onMounted(() => {
    form.nodeName = flowData.value[props.detailObject.id]?.nodeName || props.detailObject.data.label;
    form.name = props.detailObject.id;
    form.typeConcatName = `${props.detailObject.id}(${form.type}-${props.detailObject.id})`;
    form.distribute = flowData.value[props.detailObject.id]?.distribute || 'Y';

    form.remark = flowData.value[props.detailObject.id]?.remark || '';

    form.selectScriptStatus = flowData.value[props.detailObject.id]?.selectScriptStatus || '';
    form.argumentsInFields = flowData.value[props.detailObject.id]?.argumentsInFields || '';
    form.argumentFields = flowData.value[props.detailObject.id]?.argumentFields || {};
    form.processContent = flowData.value[props.detailObject.id]?.processContent || '';
    form.processContentValue = flowData.value[props.detailObject.id]?.processContentValue || '';
    monacoEditorRef.value.setData(form.processContent);

    form.outputlinedelimiter = flowData.value[props.detailObject.id]?.outputlinedelimiter || '';
    form.resultfieldname = flowData.value[props.detailObject.id]?.resultfieldname || '';
    form.errorfieldname = flowData.value[props.detailObject.id]?.errorfieldname || '';
    form.exitvaluefieldname = flowData.value[props.detailObject.id]?.exitvaluefieldname || '';

    form.isStream = flowData.value[props.detailObject.id]?.isStream || '';


})

// const changeScriptType = (value) => {
//   console.log(value)
//   if(value === 'linux'){
//     form.processContentValue = '#!/bin/bash\\n echo \\"第一个参数是: $1\\"';
//   }else {
//     form.processContentValue = '@echo off\\n echo abc%1';
//   }
//   form.processContent = form.processContentValue;
//   if(monacoEditorRef.value){
//     monacoEditorRef.value.setData(form.processContentValue)
//   }
// }

const selectedRows = ref([])
const handleSelectionChange = (val) => {
    selectedRows.value = val
}
const batchDelete = () => {
    if (selectedRows.value.length === 0) return
    const indexes = selectedRows.value.map(row =>
        form.argumentFields.argumentField.indexOf(row)
    ).sort((a,b) => b - a)
    indexes.forEach(index => {
        form.argumentFields.argumentField.splice(index, 1)
    })
    selectedRows.value = []
}
const addField = () => {
    if (!form.argumentFields.argumentField)form.argumentFields.argumentField = [];
    form.argumentFields.argumentField.push({
        argumentFieldName: ''
    });
}
const deleteField = (index) => {
    form.argumentFields.argumentField.splice(index, 1);
}

const changeTextArea = (value) => {
    console.log('changeTextArea',value)
    form.processContentValue = value;
}

const submitForm = () => {
    form.processContent = form.processContentValue;
    formRef.value.validate((valid) => {
        if (valid) {
            // 更新当前脚本内容
            form.processContent = form.processContentValue;
            flowCount.setFlowData(
                {
                    ...flowData.value,
                    [props.detailObject.id]: {
                        ...form,
                        name: `${form.type}-${form.name}`,
                    }
                }
            )
            // 触发数据更新事件
            // emit('update-data', {
            //   id: props.detailObject.id,
            //   data: form
            // });
            console.log(flowData.value);
            emit('cancel');
        } else {
            ElMessage.error('请填写结果保存项');
            return false;
        }
    });
}

const cancel = () => {
    emit('cancel');
}

const toReader = () => {

}

const parseSql = () => {
}

</script>

<style scoped>
.step-title {
    cursor: pointer;
    transition: color 0.3s;
}

.step-title:hover {
    color: #409eff;
}
.tip {
    color: #999;
    font-size: 12px;
    margin-top: 4px;
    line-height: 0.5;
}
</style>